package leetcode.design;

import leetcode.linkedlist.common.LinkedListUtils;
import leetcode.linkedlist.common.ListNode;

import java.util.List;
import java.util.Random;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution382 {

    private final Random random;
    private final List<Integer> list;
    private final int size;

    public Solution382(ListNode head) {
        random = new Random();
        list = LinkedListUtils.getLinkedListVals(head);
        size = list.size();
    }

    public int getRandom() {
        int index = random.nextInt(size);
        return list.get(index);
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */

public class leetcode382 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        ListNode head = LinkedListUtils.generateLinkedListByArray(nums);
        Solution382 solution382 = new Solution382(head);

        // getRandom() 方法应随机返回 1、2、3中的一个，每个元素被返回的概率相等。
        System.out.println(solution382.getRandom());
        System.out.println(solution382.getRandom());
        System.out.println(solution382.getRandom());
        System.out.println(solution382.getRandom());
        System.out.println(solution382.getRandom());
    }
}
